package com.ruoyi.web.core.config;

import com.alibaba.fastjson.JSON;
import com.ruoyi.web.sso.common.util.AssertUtil;
import com.ruoyi.web.sso.common.util.BusinessException;
import com.ruoyi.web.sso.common.util.ErrorCode;
import com.ruoyi.web.sso.domain.vo.RedisDetails;
import com.ruoyi.web.sso.service.IMenuService;
import com.ruoyi.web.sso.service.IRedisUtilService;
import com.ruoyi.web.sso.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.net.URL;

import static com.alibaba.druid.util.Utils.md5;


@Configuration
@Slf4j
public class Token extends WebMvcConfigurerAdapter {

    @Autowired
    private IRedisUtilService redisService;

    @Autowired
    private IMenuService menuService;

    @Bean
    public SessionInterceptor getSessionInterceptor() {
        System.out.println("bean加载了!");
        return new SessionInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSessionInterceptor());
        addInterceptor.addPathPatterns("/api/sso/**");
    }


    private class SessionInterceptor extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            //这句话是解决乱码的
            response.setHeader("Content-Type", "text/html;charset=UTF-8");

            String params = JSON.toJSONString(request.getParameterMap());
            String requestURI = request.getRequestURI();
            log.info("----------请求路径--------"+requestURI+"-------请求参数-------"+params);
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            TokenConfig methodAnnotation = handlerMethod.getMethodAnnotation(TokenConfig.class);
            if (null ==methodAnnotation){
                return true;
            }

            if ("0".equals(methodAnnotation.value())) {
                //不用管ticket
                String auth = request.getHeader("auth");
                String platform = request.getHeader("platform");
                String reqUUID = request.getHeader("uuid");
                String compVer = request.getHeader("compver");
                String url = request.getRequestURL().toString();

                if(StringUtils.isEmpty(auth) || StringUtils.isEmpty(platform) ||
                        StringUtils.isEmpty(reqUUID) || StringUtils.isEmpty(compVer) ){
                    throw new BindException(ErrorCode.UNEXPECTED_ERROR, "SessionToken异常！！");
                }

                String perferSign = authSigh(url, compVer, reqUUID, platform);
                if(!perferSign.equals(auth)){
                    throw new BindException(ErrorCode.UNEXPECTED_ERROR, "SessionToken异常！！");
                }
                return true;
            }
            RedisDetails redisDetails = null;
            //查询ticket是否存在
            try {
                String ticket = request.getHeader("ticket");
                log.info("----------ticket--------"+ticket);
                redisDetails = redisService.getTicket(ticket);

                if (AssertUtil.isEmpty(redisDetails)){
                    throw new BindException(ErrorCode.SESSION_TOKEN_ERROR, "SessionToken异常！！");
                }
                return true;
            } catch (Exception e) {
                throw new Exception("ticket不存在", e);
            }
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        }
    }

    public static String authSigh(String urlStr, String compver, String reqUuid, String platform) {
        String path = "";

        try {
            URL url = new URL(urlStr);
            path = url.getPath();
        } catch (MalformedURLException var6) {
            var6.printStackTrace();
        }

        String signBase = path + compver + reqUuid + platform + "fishstarinside";
        return md5(signBase);
    }

    public static void main(String[] args) {
        String v = "http://live.biz1.xybaby365.com/b1/xm_sb_d030.m3u8?auth_key=1697872906-0-0-abb10d27ee66b9e87e620832b299ef43&ext=.m3u8";
        System.out.println(v.substring(0,v.indexOf("?")));
    }
}